package engine

import (
	"bufio"
	"net"
	"net/http"
)

// ProxyConn 代理连接处理
type ProxyConn struct {
	conn      net.Conn
	reader    *bufio.Reader
	forwarder RequestForwarder
}

func NewProxyConn(conn net.Conn, forwarder RequestForwarder) *ProxyConn {
	return &ProxyConn{
		conn:      conn,
		reader:    bufio.NewReader(conn),
		forwarder: forwarder,
	}
}

// Close 释放连接资源
func (pc *ProxyConn) Close() error {
	if pc.conn != nil {
		return pc.conn.Close()
	}
	return nil
}

func (pc *ProxyConn) Handle() error {
	defer pc.Close()

	req, err := http.ReadRequest(pc.reader)
	if err != nil {
		return err
	}

	resp, err := pc.forwarder.Forward(req)
	if err != nil {
		return err
	}

	return resp.Write(pc.conn)
}
